<!-- 物流线路 - 表单编辑页面 -->
<template>
  	<div class="page_rela_container">
		<div class="scroll_auto flex_cell">

    <el-form ref="formEl" :model="formValue" :rules="rules"  label-width="130px" class="common-form-panel-div" >

      <ex_header_spiler title="应用参数信息"></ex_header_spiler>

      <el-row>
        <el-col style="width: 480px; margin-top: 20px;">
          <el-form-item label="所属平台" prop="platformCode">
            <ex_super_input v-model="formValue.platformCode" type="select"
                url="/open-api/open/OpenPlatformRpc/selectSimple.json" storeData
                :option="{ label: 'platformName', value: 'platformCode' }"
                @changeItem="e => { formValue.accountId = e.id;   formValue.platformName = e.platformName;   formValue.platformCode = e.platformCode; }"
                style="width: 100%;"
                :disabled="editModel"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col style="width: 480px;">
          <el-form-item label="应用名称" prop="appName">
            <el-input v-model="formValue.appName"></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col style="width: 480px;">
          <el-form-item label="应用类型" prop="openAppType">
            <el-select v-model="formValue.openAppType" placeholder="请选择" style="width:100%;">
              <el-option key="ERP" label="ERP" value="ERP"></el-option>
              <el-option key="WMS" label="WMS" value="WMS"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col style="width: 480px;">
          <el-form-item label="appId">
            <!--                <el-input v-model="" readonly></el-input>-->
            <span style="padding-left: 0px; color: #606266">{{appId}}</span>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col style="width: 420px;">
          <el-form-item label="appSecret">
            <span style="padding-left: 0px; color: #606266">{{formValue.appSecret}}</span>
          </el-form-item>
        </el-col>
        <el-col style="width: 200px; padding-left: 8px;">
          <el-button type="text" @click="$copyToClip(formValue.appSecret, 'appSecret 已复制至剪切板')" style="margin-left: 20px;">
            复制
          </el-button>
          <el-button type="text" @click="generateRandomSecret" style="margin-left: 10px;">重新生成</el-button>
        </el-col>
      </el-row>

      <el-row>
        <el-col style="width: 480px;">
          <el-form-item label="通信地址" prop="callbackUrl">
            <el-input v-model="formValue.callbackUrl"></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col style="width: 600px;">
          <el-form-item label=""  style="color: #666;" >
            <i class="el-icon-warning"></i> ERP、WMS 用于接收 KYB 接口请求的地址，需以 http/https 开头
          </el-form-item>
        </el-col>
      </el-row>

      <ex_header_spiler title="应用接口配置"></ex_header_spiler>

        <el-row>
          <el-col style="width: 800px;">
            <el-form-item label="" >
              <template v-for="group,modelIndex in apiRoot">
                <table class="api-choose-table" cellspacing="1" cellpadding="1" style="margin-top: 10px; margin-bottom: 10px;">

                    <template v-for="doc,docIndex in group.children">
                      <tr>
                        <td v-if="docIndex==0" :rowspan="group.children.length" class="choose-table-group-td">
                          {{group.name}}
                        </td>
                        <td class="choose-table-api-td">
                          <div>
                            {{doc.apiName}}
                            <span v-if="doc.apiType=='ResponseApi'" class="api-notify-tag">回传</span>
                          </div>
                          <div>
                            <el-switch v-model="doc._checked_" ></el-switch>
                          </div>
                        </td>
                      </tr>
                    </template>

                </table>
              </template>

            </el-form-item>
          </el-col>
        </el-row>


    </el-form>



  </div>
    <div class="page_rela_bottom_area">
      <el-button type="primary" @click="submitForm()">提 交</el-button>
      <el-button @click="goback()">返 回</el-button>
    </div>

  </div>

</template>


<script>

  import CodeEditor from '@/component/base/code-editor.vue'

  export default {

    title : '开放平台应用编辑',

    components: {CodeEditor},

    data() {
      return {

        formSaving: false,

        requestInterceptorVisible: false,
        responseInterceptorVisible: false,

        appId: '',

        formValue: {
          'appSecret': '',
          'platformCode': '',
          'accountId': ''
        },
        codeForm: {},

        apiRoot: [],

        rules: {
          platformCode:[
            {required: true, message: '所属平台', trigger: 'blur'}
          ],
          appName: [
            {required: true, message: '请输入应用名称', trigger: 'blur'}
          ],
          openAppType: [
            {required: true, message: '应用类型', trigger: 'blur'}
          ],
          // callbackUrl: [
          //   {required: true, message: '请输入回传地址', trigger: 'callbackUrl'}
          // ]
        },

        editModel: false

      };
    },

    watch: {
      'formValue.openAppType'(val, old){
        if(val == 'ERP'){
          this.apiRoot = this.erpGroups
        }
        else if(val == 'WMS'){
          this.apiRoot = this.wmsGroups
        }
        else{
          this.apiRoot = []
        }
      }

    },

    created() {
      let _this = this

      _this.submitUrl = '/open-api/open/OpenApiConfigRpc/saveUpdateApp.json'

      let formId = this.$route.query.id

      _this.formId = formId

      if(formId){
        _this.editModel = true
      }

      if (!_this.formId) {
        _this.generateRandomId();
        _this.generateRandomSecret()
      }
      _this.loadAllApis()

    },

    mounted() {
      var _this = this;

    },

    destroyed() {
    },

    methods: {

      generateRandomId() {
        let _this = this
        _this.$ajax({
          url: '/open-api/open/OpenApiConfigRpc/getRandomId.json',
          success: function (res) {
            if (res && res.data) {
              _this.appId = res.data
              //_this.formValue.appId = res.data
              // _this.formValue = _this.formValue
            }
          }
        })
      },

      generateRandomSecret() {

        let tmps = '01234567890abcdefghijklmnopqrstuvwxyz=+-'
        let len = 32
        let output = ''
        for (let i = 0; i < len; i++) {
          let index = parseInt(Math.random() * tmps.length)
          output += tmps.substring(index, index + 1)
        }

        this.formValue.appSecret = output

      },

      submitDone() {

      },

      initCheckForms(docs, checkedMap){

        let _this = this

        _this.erpGroups = docs.ERP
        _this.wmsGroups = docs.WMS

        _this.erpGroups.forEach(group => {
          group.children.forEach(c => {
            c._checked_ = checkedMap[c.apiUrl] ? true : false
          })
        })
        _this.wmsGroups.forEach(group => {
          group.children.forEach(c => {
            c._checked_ = checkedMap[c.apiUrl] ? true : false
          })
        })

      },


      loadAllApis() {

        let _this = this

        _this.$getAllDocs(function (docsResults) {

          if (_this.formId) {
            _this.$ajax({
              url: '/open-api/open/OpenApiConfigRpc/getAppDetail.json?id=' + _this.formId,
              success: function (res) {

                let checkedMap = {}

                if (res && res.data) {
                  _this.formValue = res.data
                  _this.appId = _this.formValue.appId

                  if (_this.formValue.apiUrls) {
                    _this.formValue.apiUrls.forEach(tmpUri => {
                      checkedMap[tmpUri] = true
                    })
                  }
                }
                _this.initCheckForms(docsResults, checkedMap)
              }
            })

          }
          else{
            _this.initCheckForms(docsResults, {})
          }
        })

      },

      submitForm() {

        let _this = this
        let arr = []

        _this.apiRoot.forEach(tgp=>{

          if(!tgp || tgp.children.length == 0){
            return
          }
          tgp.children.forEach(tmpDoc=>{
            if(tmpDoc._checked_){
              arr.push(tmpDoc.apiUrl)
            }
          })

        })


        this.formValue.appId = this.appId
        this.formValue.apiUrls = arr

        _this.$refs['formEl'].validate((valid) => {
          if (valid) {

            _this.$ajax({
              url: '/open-api/open/OpenAppRpc/saveUpdateApp.json',
              type: 'json',
              data: _this.formValue,
              success: (responseData) => {
                this.$message({
                  showClose: true,
                  message: '提交成功',
                  type: 'success'
                })

                _this.$tag.tagClose()
              }
            });

          } else {
            return false;
          }

        });


      },

      goback() {
        this.$tag.tagClose()
      }

    }
  }

</script>
<style>
  .db_clear_list .el-checkbox {
    width: 600px;
    line-height: 30px;
  }

  .resource-div-block {
    display: flex;
    flex-flow: row wrap;
    justify-content: flex-start;
    align-items: center;
  }

  .resource-div-block div {
    padding: 14px 40px 14px 40px;
    margin-bottom: 14px;
    font-size: 28px;
    color: #409eff;
    background: #ecf5ff;
    border-color: #b3d8ff;
    margin-right: 20px;
    cursor: pointer;
    position: relative;
  }

  .api-choose-table {
    background-color: #ececec;
    width: 100%;
  }

  .api-choose-table td {
    background-color: #fff;
    padding: 0px 8px 0px 8px;
    line-height: 42px;
  }

  .api-choose-table .choose-table-group-td {
    vertical-align: top;
    width: 140px;
  }

  .api-choose-table .choose-table-api-td {
    display: flex;
    justify-content: space-between;
  }

  .api-notify-tag {
    background-color: #fff;
    color: #81b1ff;
    border: 1px solid #81b1ff;
    border-radius: 4px;
    padding: 0px 2px;
  }

  .api-choose-label .el-form-item__label {
    padding-top: 5px;
  }
</style>
